// pages/answer/answer.js
const qcloud = require('../../vendor/qcloud-weapp-client-sdk/index.js')
const config = require('../../config.js')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    offsetH:0,
    radioVal: '', //单选和判断选中答案
    result: '', //对错返回值
    index: 0, //题目索引
    answerSerial:['A','B','C','D','E','F','G'], //答案序号
    checkboxArray: [], //多选答案参数
    questionDTOs: [], //题目数据
    questionOptions: [],//题目列表
    judgeList: [{ "optionNo": "0", "content": "对" }, { "optionNo": "1", "content": "错" }], //判断题答案
    totalTime: 6, //总时间
    HalfTime: 3, // 总时间的一半
    timeIndex: 0, //倒计时计时器
    rotateVal: 0, // 旋转度
    times: '',
    resultQuestionVOsJn: [],
    questionDTOsAnswer:''
  },

  //倒计时结束显示当前正确答案
  setAnswer() {
    let questionDTOs = this.data.questionDTOs[this.data.index]
    let curType = questionDTOs.type;

    if (curType == 1) {
      let questionOptions = this.data.questionOptions
      let questionDTOs = this.data.questionDTOs[this.data.index]
      let rightAnswer = JSON.parse(questionDTOs.rightAnswer.replace(/(\d+)/g, '$1'))
      for (var i = 0; i < questionOptions.length; i++) {
        var optionNo = Number(questionOptions[i].optionNo)
       
        
        if (rightAnswer.indexOf(optionNo) > -1) {
          questionOptions[i].correct = true
        } else {
          questionOptions[i].correct = false
        }
      }

      this.setData({
        questionOptions: questionOptions
      })

    } else {
      this.setData({
        questionDTOsAnswer: questionDTOs.rightAnswer
      })
    }
  },

  //倒计时
  countdown() {

    let times;
    let questionDTOs = this.data.questionDTOs[this.data.index]
    let curType = questionDTOs.type;
    let globalData = getApp().globalData

    let setTime = [globalData.limitSecondsSingle, globalData.limitSecondsMultiple, globalData.limitSecondsChecking]
    //0 单选 1 多选 2判断

    this.setData({
      totalTime: setTime[curType]
    }) 

    this.setData({
      HalfTime: this.data.totalTime / 2
    })

    this.setData({
      timeIndex: this.data.totalTime
    })

    this.setData({
      rotateVal: 360 / this.data.totalTime
    })
    
    this.setAnswer()

    this.data.times = setInterval(() => {
      this.setData({
        timeIndex: this.data.timeIndex - 1
      })

      if (this.data.timeIndex <= 0) {
        clearInterval(this.data.times)

        if (this.data.result !== true && this.data.result !== false) {
          this.setData({
            radioVal: 'no'
          })

          this.setData({
            result: false
          })
        }

        this.resultFn()

        setTimeout(() => {
          this.curParam()
        }, 2000)
      }
    }, 1000)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    qcloud.request({
      url: config.service.obtainPaberQusetions,
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      login: true,
      data: {
        'epId': options.epId
      },
      success: (response) => {
        var data = response.data
        if (data.code === 0) {

          this.setData({
            questionDTOs: data.questionDTOs
          })

          this.setData({
            questionOptions: data.questionDTOs[this.data.index].questionOptions.sort((a,b) => {
              return Math.random() > 0.5 ? 1 : -1;
            })
          })

          this.countdown()
        } else {
          wx.showToast({
            title: '系统错误!',
            image: "../../images/error.png",
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function (err) {
        console.log(err);
      }
    });


  },

  // 页面离开
  onUnload:function() {
    clearInterval(this.data.times)
  },

  //初始化参数
  curParam() {
    clearInterval(this.data.times)
    if (this.data.index >= this.data.questionDTOs.length - 1) {
      clearInterval(this.data.times)
      
      wx.redirectTo({
        url: '/pages/result/result'
      })

      app.globalData.resultQuestionVOsJn = this.data.resultQuestionVOsJn

    } else {
      this.setData({
        index: this.data.index + 1
      })

      this.setData({
        timeIndex: 0
      })

      this.setData({
        questionOptions: this.data.questionDTOs[this.data.index].questionOptions.sort((a, b) => {
          return Math.random() > 0.5 ? 1 : -1;
        })
      })


      this.setData({
        radioVal: ""
      })

      this.setData({
        result: ""
      })


      this.countdown()
    }
  },

  //存储答题数据
  resultFn() {
    let globalData = getApp().globalData
    let resultQuestionVOsJn = this.data.resultQuestionVOsJn
    let questionDTOs = this.data.questionDTOs[this.data.index]
    let setTime = [globalData.limitSecondsSingle, getApp().globalData.limitSecondsMultiple, getApp().globalData.limitSecondsChecking]

    resultQuestionVOsJn[this.data.index] = {
      'eqId': questionDTOs.eqId,
      'limitSeconds': setTime[questionDTOs.type],
      'rightAnswer': questionDTOs.rightAnswer,
      'score': !!this.data.result ? 10 : 0,
      'answerCorrect': this.data.result,
      'type': questionDTOs.type,
      'usedSeconds': (this.data.totalTime - this.data.timeIndex) <= 0 ? 1 : (this.data.totalTime - this.data.timeIndex),
      'userAnswer': questionDTOs.type == 1 ? this.data.checkboxArray : this.data.radioVal
    }
    
    this.setData({
      resultQuestionVOsJn: resultQuestionVOsJn
    })

  },

  //多选
  checkboxChange: function (e) {
    let checkArr = e.detail.value.map(Number);
    let questionOptions = this.data.questionOptions
    let questionDTOs = this.data.questionDTOs[this.data.index]
    let rightAnswer = JSON.parse(questionDTOs.rightAnswer).map(Number)

    this.setData({
      checkboxArray: e.detail.value
    })

    e.detail.value = []

    for (var i = 0; i < questionOptions.length; i++) {
      var optionNo = questionOptions[i].optionNo

      if (rightAnswer.indexOf(optionNo) > -1) {
        questionOptions[i].correct = true 
      } else {
        questionOptions[i].correct = false 
      }

      if (checkArr.indexOf(optionNo) > -1) {
        questionOptions[i].checked = true
      } else {
        questionOptions[i].checked = false
      }
    }
    
    this.setData({
      questionOptions: questionOptions
    })

    if (rightAnswer.length === this.data.checkboxArray.length) {
      this.setData({
        result: this.data.checkboxArray.sort().toString() == rightAnswer.sort().toString()
      })

      this.setData({
        radioVal: this.data.checkboxArray
      })

      this.resultFn()
      clearInterval(this.data.times)

      setTimeout(() => {
        this.curParam()
      }, 2500)
    }
    
  },

  //单选
  radioChange(e) {
    let questionDTOs = this.data.questionDTOs[this.data.index]
    this.setData({
      radioVal: e.detail.value
    })


    e.detail.value = ''

    this.setData({
      result: questionDTOs.rightAnswer == this.data.radioVal
    })

    this.setData({
      questionDTOsAnswer: questionDTOs.rightAnswer
    })

    this.resultFn()
    clearInterval(this.data.times)

    setTimeout(() => {
      this.curParam()
    }, 2000)

  },

  onShow(){
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          offsetH: res.windowHeight
        })
      }
    })
  }

})